package com.example.administrator.myapplication;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class PlaylistDownloader2 {
    private URL url;
    private List<String> playlist;
    private Boolean isNew;
    private ParseListener mListener;
    private static final String BANDWIDTH = "BANDWIDTH";

    public interface ParseListener{
        //在你的Activity或者fragment中，将会从该方法中获取到数据
        void parseResult(ArrayList<M3u8Source> list);
    }

    /**
     * @param url 从服务器获取的master playlist m3u8文件
     * @param isNewParseFun false:旧的解析方法 true:新的解析方法
     */
    public PlaylistDownloader2(URL url, Boolean isNewParseFun ) {
        this.url = url;
        playlist = new ArrayList<>();
        isNew = isNewParseFun;
    }

    public void parse(ParseListener listener) throws IOException {
        mListener = listener;
        new FetchPlaylist().execute();
    }


    private class FetchPlaylist extends AsyncTask<Void, Void, ArrayList<M3u8Source>> {
        boolean isMaster = false;

        @Override
        protected ArrayList<M3u8Source> doInBackground(Void... voids) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(url.openStream()));


                String line;
                while ((line = reader.readLine()) != null) {
                    playlist.add(line);

                    if (line.contains(BANDWIDTH))
                        isMaster = true;
                }

                reader.close();
            } catch (IOException e) {
                Log.e("msg","Exception");
                e.printStackTrace();
            }

            //用于存储最终返回的视频源列表
            ArrayList<M3u8Source> m3u8SourcesList = new ArrayList<>();
            for (int i = 0; i < playlist.size(); i++) {
                String s = playlist.get(i);
                //从有BANDWIDTH 那一行开始处理
                if (s.contains(BANDWIDTH)) {
                    M3u8Source m3u8Source = new M3u8Source();
                    try {
                        //********开始截取带宽  暗指清晰度*********//*
                        int pos = s.lastIndexOf(BANDWIDTH+"=") + 10;
                        int end = s.indexOf(",",pos);
                        if (end < 0 || end < pos) end = s.length()-1;
                        long bandwidth = Long.parseLong(s.substring(pos, end));
                        //********结束截取带宽  暗指清晰度*********//*

                        m3u8Source.setVideoResolution(bandwidth);//存储带宽
                        int urlindex = i + 1;//带宽的下一行是地址，所以这么写
                        String sub = playlist.get(urlindex);
                        m3u8Source.setVideoRealUrl(updateUrlForSubPlaylist(sub,bandwidth,isNew).toString());

                        m3u8SourcesList.add(m3u8Source);
                    } catch (NumberFormatException ignore) {
                        Log.i("msg","NumberFormatException"+ignore.getMessage());
                    }

                }
            }

            return m3u8SourcesList.size()>0?m3u8SourcesList:null;
        }

        @Override
        protected void onPostExecute(ArrayList arrayList) {
            super.onPostExecute(arrayList);
            if (arrayList != null) {
                ArrayList<M3u8Source> m3u8SourceList = new ArrayList<>();
                m3u8SourceList = arrayList;
                if (m3u8SourceList.size()>0) {
                    mListener.parseResult(m3u8SourceList);
                }
            }
        }
    }

    /**
     * 拼装真实的播放源地址
     * @param sub
     * @return
     */
    private URL updateUrlForSubPlaylist(String sub,long bindwidth,boolean isNew) {
        String newUrl;
        URL aUrl = null;

        if (!sub.startsWith("http")) {
            if (isNew) {
//                newUrl = new StringBuffer(getBaseUrl2(this.url)).append("/").append(sub.substring(0,sub.length()-5)).append("/").append(String.valueOf(bindwidth / 1000)).append("kb/hls/index.m3u8").toString();
                newUrl = new StringBuffer(getBaseUrl1(this.url)).append(String.valueOf(bindwidth / 1000)).append("kb/hls/index.m3u8").toString();
            }else {
                if (sub.startsWith("/")) {
                    newUrl = getBaseUrl2(this.url) + sub.substring(1,sub.length());
                }else {
                    newUrl = getBaseUrl2(this.url) + sub;
                }

            }
        } else {
            newUrl = sub;
        }

        try {
            aUrl = new URL(newUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return aUrl;
    }

    /**
     * 旧旧旧旧旧旧旧的解析方法
     * 去掉最后一个/后面的内容并拼接数据
     * @param url
     * @return
     */
    private String getBaseUrl1(URL url) {
        String urlString = url.toString();
        int index = urlString.lastIndexOf('/');
        return new StringBuffer(urlString.substring(0, index)).append("/").toString();
    }

    /**
     * 新新新新新新新的解析方法
     * 域名之后的第一个/之后都去掉并拼接
     * @param url
     * @return
     */
    private String getBaseUrl2(URL url) {
        String urlString = url.toString();
        String[] split = urlString.split("://");
        String s = split[1];

        String[] split1 = s.split("/");
        StringBuffer append = new StringBuffer(split[0]).append("://").append(split1[0]).append("/");

        return append.toString();
    }

}
